﻿using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System;
using System.Linq;
using System.Windows.Controls;
using System.Text.RegularExpressions;

namespace GMUtilitiesDotNet.AttachedProperties
{
    public static class TextBoxSelectAllOnFocus
    {
        public static readonly DependencyProperty IsEnabledProperty =
                DependencyProperty.RegisterAttached("IsEnabled",
                    typeof(bool), typeof(TextBoxSelectAllOnFocus),
                        new UIPropertyMetadata(false, OnEnabledStateChanged));

        /// <summary>
        /// Attached Property getter for the IsEnabled property.
        /// </summary>
        /// <param name="source">Dependency Object</param>
        /// <returns>Current property value</returns>
        public static bool GetIsEnabled(DependencyObject source)
        {
            return (bool)source.GetValue(IsEnabledProperty);
        }

        /// <summary>
        /// Attached Property setter for the IsEnabled property.
        /// </summary>
        /// <param name="source">Dependency Object</param>
        /// <param name="value">Value to set on the object</param>
        public static void SetIsEnabled(DependencyObject source, bool value)
        {
            source.SetValue(IsEnabledProperty, value);
        }

        private static void OnEnabledStateChanged(DependencyObject sender,
                DependencyPropertyChangedEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb == null)
                return;

            tb.GotFocus -= tb_GotFocus;
            tb.MouseDoubleClick -= tb_GotFocus;
            tb.PreviewMouseLeftButtonDown -= tb_PreviewMouseLeftButtonDown;
                                    
            bool b = ((e.NewValue != null && e.NewValue.GetType() == typeof(bool))) ?
                (bool)e.NewValue : false;

            if (b)
            {
                tb.GotFocus += tb_GotFocus;
                tb.MouseDoubleClick += tb_GotFocus;
                tb.PreviewMouseLeftButtonDown += tb_PreviewMouseLeftButtonDown;
            }
        }

        private static void tb_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb != null)
            {
                if (!tb.IsKeyboardFocusWithin)
                {
                    e.Handled = true;
                    tb.Focus();
                }
            }
        }
        private static void tb_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if(tb != null)
            {
                tb.SelectAll();
            }
        }
    }
}
